

import { Button, Checkbox,Input,message,Modal, Radio,Space } from 'antd';
import Avatar from 'antd/lib/avatar/avatar';
import { publish } from 'pubsub-js';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { connect } from 'react-redux';
import { getGroupDismiss, getGroupMember, getGroupQuit, getUpdateGroupCreator, getUpdateGroupSet } from '../../../../assets/js/api';
import { imgUrlDev } from '../../../../assets/js/tools';
import { closeGroupInfo } from '../../../../event-type';
import {
    group_info_set,
    group_info_set_row,
    group_info_set_tip,

    group_info_quit_btn,
    
    dismiss_modal_top,
    dismiss_modal_bottom,
    dismiss_modal_group_info,
    dismiss_modal_group_avator,
    dismiss_modal_group_name,
    dismiss_modal_group_create_time,
    dismiss_modal_tip,
    dismiss_modal_member_list,
} from './index.module.css';

function GroupSet(props) {

    const {group_public,group_id,identity,user,currentRoomInfo} = props;

    const [members, setMembers] = useState([]);
    const [memberError, setMemberError] = useState(false);
    
    const [quitModalVisible, setQuitModalVisible] = useState(false);
    const [dismissCheckModalVisible, setDismissCheckModalVisible] = useState(false);
    const [dismissCheckModalTxt, setDismissCheckModalTxt] = useState('');
    const [dismissCheckModalOk, setDismissCheckModalOk] = useState('');
    
    const [dismissModalVisible, setDismissModalVisible] = useState(false);
    const [transferTarget, setTransferTarget] = useState(-1);       // 转让目标用户id
    const [filterMemberKeyword, setFilterMemberKeyword] = useState('');

    const filteredMember = useMemo(
        () => {
            // 关键字过滤并按权限排序
            const filterMembers = members.filter(item => item.user_name.includes(filterMemberKeyword))
            const creator = [];
            const admin = [];
            const people = [];
            for (let i = 0; i < filterMembers.length; i++) {
                if (filterMembers[i].member_type === '3') {
                    creator.push(filterMembers[i]);
                    continue;
                }
                if (filterMembers[i].member_type === '2') {
                    admin.push(filterMembers[i]);
                    continue;
                }
                if (filterMembers[i].member_type === '1') {
                    people.push(filterMembers[i]);
                    continue;
                }
            }
            return creator.concat(admin, people);
        }, 
        [filterMemberKeyword, members]
    )

    const dismissGroup = useCallback(() => {
        // 此函数需要存放进useState,而函数存放useState会自执行一次
        return () => {
            getGroupDismiss({group_id,user_id:user.id})
            .then(res => {
                const {code,message:content} = res.data;
                if (code !== 1) {
                    console.log(res.data)
                    message.open({type:'error', content});
                    return;
                }
                setDismissModalVisible(false);
                setDismissCheckModalVisible(false);
                publish(closeGroupInfo);
            })
            .catch(err => {
                console.log(err);
            });
        }
    }, [group_id, user]);
    const transferGroup = useCallback(() => {
        return () => {
            // // 移交群主
            getUpdateGroupCreator({group_id,user_id:user.id,target_id: transferTarget})
            .then(res => {
                const {code} = res.data;
                if (code === 1) {
                    publish(closeGroupInfo);
                    setDismissModalVisible(false);
                    setDismissCheckModalVisible(false);
                }
            })
            .catch(err => {
                console.log(err);
            });
        }
    }, [group_id, user, transferTarget]);

    useEffect(() => {
        if (!group_id) return;
        getGroupMember({group_id})
        .then(res => {
            const {code, data} = res.data;
            if (code === 1) {
                setMembers(data);
                setMemberError(false);
            } else {
                setMemberError(true);
            }
        })
        .catch(err => {
            console.log(err);
            setMemberError(true);
        });
    }, [group_id]);


    function formatDate(time) {
        const dateTime = new Date(time);
        return `${dateTime.getFullYear()}/${dateTime.getMonth() + 1}/${dateTime.getDate()}`;
    }
    function quitGroupCheck() {
        // 退出群组
        if (identity === 3) {
            // 群主退出 需要先转让或解散
            setDismissModalVisible(true);
            return;
        }
        setQuitModalVisible(true);
    }
    function groupSetChange(value, attr) {
        // 更改群组设置

        getUpdateGroupSet({group_id,attr,value:(value?'1':'0')})
        .then(res => {
            const {code, messaege} = res.data;
            if (code !== 1) {
                console.log(messaege);
                return;
            }
            setQuitModalVisible(false);
        })
        .catch(err => {
            console.log(err);
        });
    }
    function confrimQuitGroup() {
        // 确认退出群组
        getGroupQuit({group_id,user_id: user.id})
        .then(res => {
            const {code, message: content} = res.data;
            if (code !== 1) {
                message.open({type: 'error', content});
                return;
            }
        })
        .catch(err => {
            console.log(err);
            message.open({type: 'error', content: err.message});
            return;
        })
        .finally(() => {
            setQuitModalVisible(false);
            publish(closeGroupInfo);
        });
    }
    function confirmChose(txt, func) {
        setDismissCheckModalTxt(txt);
        setDismissCheckModalOk(func);
        setDismissCheckModalVisible(true);
    }



    return (
        <>
            <div className={group_info_set}>
                <div className={group_info_set_row}>
                    {
                        identity > 1 ?
                            <Checkbox 
                                defaultChecked={group_public === '1'}
                                onChange={e => groupSetChange(e.target.checked,'public')}
                            /> : 
                            ''
                    }
                    <span className={group_info_set_tip}>公开显示群组</span>
                </div>
                <div className={group_info_set_row}>
                    <button className={group_info_quit_btn} onClick={quitGroupCheck}>退出该群</button>
                </div>
            </div>
            <Modal
                visible={quitModalVisible}
                title={null}
                cancelText="取消"
                okText="确认"
                zIndex={1001}
                onCancel={() => setQuitModalVisible(false)}
                onOk={confrimQuitGroup}
            >
                是否退出群组？（退群通知仅通知管理员）
            </Modal>
            <Modal
                title="解散该群"
                footer={
                    <>
                        <Button disabled={transferTarget === -1} onClick={() => {confirmChose('是否要将群主转让？', transferGroup)}}>转让</Button>
                        <Button onClick={() => {confirmChose('是否要解散群组？', dismissGroup)}}>解散</Button>
                    </>
                }
                width={300}
                zIndex={1001}
                visible={dismissModalVisible}
                onCancel={() => {
                    setDismissModalVisible(false);
                    setTransferTarget(-1);
                    setMemberError(false);
                    setFilterMemberKeyword('');
                }}
            >
                <div className={dismiss_modal_top}>
                    <div className={dismiss_modal_group_info}>
                        <Avatar className={dismiss_modal_group_avator} src={imgUrlDev(currentRoomInfo.group_avator)} size={60} />
                        <span className={dismiss_modal_group_name}>{currentRoomInfo.group_name}</span>
                        <span className={dismiss_modal_group_create_time}>{formatDate(currentRoomInfo.create_time)}</span>
                    </div>
                    <span className={dismiss_modal_tip}>你是群主，可以选择转让或者解散群组，建议转让群。</span>
                </div>
                <div className={dismiss_modal_bottom}>
                    <Input 
                        placeholder="搜索群成员" 
                        size='small'
                        value={filterMemberKeyword} 
                        onChange={e=>setFilterMemberKeyword(e.target.value)}
                    />
                    <span className={dismiss_modal_tip}>请选择要转让的群员</span>
                        {
                            memberError ?
                                <div className={dismiss_modal_member_list} style={{
                                    display: 'flex', 
                                    alignItems: 'center', 
                                    justifyContent: 'center', 
                                    color: '#f00'
                                }}>网络错误，请稍后重试</div> :
                                filteredMember.length > 0 ?
                                    <Radio.Group
                                        className={dismiss_modal_member_list}
                                        value={transferTarget}
                                        onChange={e => setTransferTarget(e.target.value)}
                                    >
                                        <Space direction="vertical" size={0}>
                                            {
                                                filteredMember.map(item => (
                                                    <Radio 
                                                        key={item.user_id} 
                                                        disabled={item.user_id === user.id}
                                                        value={item.user_id} 
                                                        style={{alignItems:'center',width: '100%',fontSize: '16px'}}
                                                    >
                                                        <div style={{display:'flex',alignItems:'center',justifyContent:'center',height: '30px',lineHeight: '30px'}}>
                                                            <Avatar src={imgUrlDev(item.user_avator)} size={22} style={{marginRight: '6px'}}/>
                                                            <span>{item.user_name}</span>
                                                        </div>
                                                    </Radio>
                                                ))
                                            }
                                        </Space>
                                    </Radio.Group>:
                                    <div className={dismiss_modal_member_list} style={{
                                        display: 'flex', 
                                        alignItems: 'center', 
                                        justifyContent: 'center' 
                                    }}>无搜索结果...</div>
                        }
                </div>
            </Modal>
            <Modal 
                title={null}
                cancelText="取消"
                okText="确认"
                zIndex={1002}
                visible={dismissCheckModalVisible}
                onCancel={() => setDismissCheckModalVisible(false)}
                onOk={dismissCheckModalOk}
            >
                {dismissCheckModalTxt}
            </Modal>
        </>
    )
}

function mapStateToProps(state) {
    return {
        user: state.user,
        currentRoomInfo: state.currentRoomInfo
    }
}
export default connect(
    mapStateToProps,
    {

    }
)(GroupSet);

